import { defineComponent, ref } from 'vue'
import valiDate from '@/utils/validate'
import { useFullscreen } from '@vueuse/core'
import type { FormRules, FormItemRule, FormInst } from 'naive-ui'

import { getValidateLabel } from '@/enum/validateEnum'
import MacHeader from '@/components/codeBlock/MacHeader'
import pageStyle from '../../styles/rule.module.scss'
import { useMessage, NModal, NForm, NFormItem, NInput, NButton } from 'naive-ui'
export default defineComponent({
  setup(props, { expose }) {
    const modalRef = ref()
    const { isFullscreen, toggle } = useFullscreen(modalRef)

    const formRef = ref<FormInst | null>(null)
    const queryForm: any = ref({
      value: ''
    })
    let valName = ''
    const rules: FormRules = {
      value: {
        required: true,
        validator(rule: FormItemRule, value: string) {
          if (valName.includes('is')) {
            if (!valiDate[valName](value)) {
              return new Error(`${getValidateLabel(valName)}格式不正确`)
            }
          } else if (!eval(valName).test(value)) {
            return new Error(`格式不正确`)
          }
          return true
        },
        trigger: ['input', 'blur']
      }
    }

    const message = useMessage()
    const handSave = () => {
      formRef.value?.validate(errors => {
        if (errors) {
          return
        }
        message.success('验证通过')
      })
    }

    const show = ref(false)
    const close = () => {
      show.value = false
    }

    const open = (e: string) => {
      valName = e
      queryForm.value = {
        value: ''
      }
      show.value = true
    }

    expose({
      open
    })
    return () => (
      <NModal show={show.value} onUpdateShow={close}>
        <div ref={modalRef} class={pageStyle.ruleTestModal}>
          <MacHeader
            title="正则验证"
            is-fullscreen={isFullscreen.value}
            onToggle={toggle}
            onClose={close}
          />
          <div class="content">
            <NForm ref={formRef} model={queryForm.value} rules={rules}>
              <NFormItem label="值" path="value">
                <NInput v-model:value={queryForm.value.value} placeholder="请输入值" />
              </NFormItem>
            </NForm>
            <div class="mt-[30px] btns flex item-center justify-end">
              <NButton onClick={close}>
                <span>取消</span>
              </NButton>
              <NButton style={{ marginLeft: '10px' }} type="primary" onClick={handSave}>
                <span>验证</span>
              </NButton>
            </div>
          </div>
        </div>
      </NModal>
    )
  }
})
